﻿using System;
using System.Collections.Generic;

using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using KPIS.GERP.ESS.APP.App_UI.Commons;
using Telerik.Web.UI;
using System.Data;
using System.Collections;
using KPIS.GERP.ESS.BLL;
using KPIS.GERP.ESS.MODEL;

namespace KPIS.GERP.ESS.APP.App_UI.UserControls
{
    public partial class MailActivity : System.Web.UI.UserControl
    {
        private B_HrmPositions posBLL = new B_HrmPositions();
        private B_MessageSend sendBLL = new B_MessageSend();
        private B_MessageReply replyBLL = new B_MessageReply();
        private HrmActivityBLL actBLL = new HrmActivityBLL();

        private const int ItemsPerRequest = 10;
        private bool bRequest = false;
        protected void Page_Load(object sender, EventArgs e)
        {

        }
        protected bool IsUserControlPostBack
        {
            get
            {
                return this.ViewState["IsUserControlPostBack"] != null;
            }
        }
        protected override void OnLoad(System.EventArgs e)
        {
            base.OnLoad(e);

            if (!IsUserControlPostBack)
            {
                this.ViewState.Add("IsUserControlPostBack", true);
            }
        }
        public void LoadDetail(Nullable<int> SendSequence, Nullable<int> Sequence, bool bEdit)
        {
            PanelRequest.Visible = !bRequest;
            PanelApproved.Visible = bRequest;
            cmdRegister.Visible = !bRequest && bEdit;
            cmdApproved.Visible = bRequest && bEdit;

            DataSet ListDataCommand = actBLL.LoadActivity(Sequence, (int?)null, null, null);

            lblSendSequence.Text = SendSequence.ToString();
            UpdateSendMessageStatus(lblSendSequence.Text, SystemInfo._ReadMessage);                

            if (ListDataCommand.Tables.Count > 0)
            {
                DataTable table = ListDataCommand.Tables[0];
                if (table.Rows.Count > 0)
                {
                    lblActSequence.Text = table.Rows[0]["act_seq"].ToString();
                    lbActDescr.Text = table.Rows[0]["bgm_proj_oper_name"].ToString();
                    lbLocation.Text = table.Rows[0]["location_text"].ToString();
                    lbcity.Text = table.Rows[0]["city_name"].ToString();
                    lbCountry.Text = table.Rows[0]["country_name"].ToString();
                    lbSchedule.Text = table.Rows[0]["job_site_name"].ToString();
                    lbDateSignStard.Text = string.Format("{0:d MMMM yyyy}", table.Rows[0]["date_sign_start"]);
                    lbDateSignEnd.Text = string.Format("{0:d MMMM yyyy}", table.Rows[0]["date_sign_end"]);
                    lbDateActStard.Text = string.Format("{0:d MMMM yyyy}", table.Rows[0]["date_activity_start"]);
                    lbDateActEnd.Text = string.Format("{0:d MMMM yyyy}", table.Rows[0]["date_activity_end"]);
                    lblAppDateStart.Text = string.Format("{0:d MMMM yyyy}", table.Rows[0]["date_app_start"]);
                    lblAppDateEnd.Text = string.Format("{0:d MMMM yyyy}", table.Rows[0]["date_app_end"]);
                    lbActLimit.Text = table.Rows[0]["act_limit"].ToString();
                    lbRemark.Text = table.Rows[0]["remarks"].ToString();
                    lblAttendCount.Text = table.Rows[0]["attend_count"].ToString();

                }
            }

        }
        public void LoadMessageSend(string Sequence)
        {
            bRequest = true;

            M_MessageSend infoList = sendBLL.GetInfo(Sequence);

            if (infoList != null)
            {
                lblApprovedBy.Text = infoList.to_emp_seq.ToString();
                lblReceiveName.Text = infoList.to_user_name;
                lblSenderSequence.Text = infoList.from_emp_seq.ToString();
                lblSenderName.Text = infoList.from_user_name;
                lblSendText.Text = infoList.send_text;
                lblRefSequence.Text = infoList.ref_seq.ToString();
            }
        }
        protected void UpdateSendMessageStatus(string strSendSeq, string strMessageStatus)
        {
            M_MessageSend info = new M_MessageSend();

            info.send_seq = Convert.ToInt32(strSendSeq);
            info.message_status = strMessageStatus;
            info.updated_by = Int32.Parse(Session["EmpSeq"].ToString());
            info.updated_when = DateTime.Now;

            sendBLL.UpdateMessageStatus(info);
        }
        protected void cmbApprover_ItemsRequested(object o, RadComboBoxItemsRequestedEventArgs e)
        {
            cmbApprover.Items.Clear();

            DataSet ds = posBLL.GetPositionUpper(Int32.Parse(Session["EmpSeq"].ToString()), (int?)null, e.Text);
            DataTable dt = null;
            if (ds.Tables.Count > 0)
            {
                dt = ds.Tables[0];

                int itemOffset = e.NumberOfItems;
                int endOffset = Math.Min(itemOffset + ItemsPerRequest, dt.Rows.Count);
                e.EndOfItems = (endOffset == dt.Rows.Count);
                int j = 0;
                for (int i = itemOffset; i < endOffset; i++)
                {
                    cmbApprover.Items.Add(new RadComboBoxItem(dt.Rows[i]["FULL_NAME"].ToString(), dt.Rows[i]["UPPER_EMP_SEQ"].ToString()));
                    j++;
                }
            }
        }

        protected void rdoApproveStatus_SelectedIndexChanged(object sender, EventArgs e)
        {
            bool bNotApproved = rdoApproveStatus.SelectedValue == "0";
            bool bNext = rdoApproveStatus.SelectedValue == "F";

            // กรณีไม่เห็นด้วย
            //lblApprovedReasonTitle.Visible = bNotApproved;
            //txtApprovedReason.Visible = bNotApproved;

            //// กรณีส่งให้พิจารณาต่อ
            //lblNextApprovedTitle.Visible = bNext;
            cmbNextApprover.Enabled = bNext;
        }
        protected void cmbNextApprover_ItemsRequested(object o, RadComboBoxItemsRequestedEventArgs e)
        {
            cmbNextApprover.Items.Clear();

            DataSet ds = null;
            ds = posBLL.GetPositionUpper(Int32.Parse(lblApprovedBy.Text), (int?)null, e.Text);
            DataTable dt = null;
            if (ds.Tables.Count > 0)
            {
                dt = ds.Tables[0];

                int itemOffset = e.NumberOfItems;
                int endOffset = Math.Min(itemOffset + ItemsPerRequest, dt.Rows.Count);
                e.EndOfItems = (endOffset == dt.Rows.Count);
                int j = 0;
                for (int i = itemOffset; i < endOffset; i++)
                {
                    cmbNextApprover.Items.Add(new RadComboBoxItem(dt.Rows[i]["FULL_NAME"].ToString(), dt.Rows[i]["UPPER_EMP_SEQ"].ToString()));
                    j++;
                }
            }
        }
        protected void cmdRegister_Click(object sender, EventArgs e)
        {
            M_MessageSend sendInfo = new M_MessageSend();

            sendInfo.send_date = DateTime.Today;
            sendInfo.ref_no = sendBLL.GetNextSendRefNo("AC");
            sendInfo.send_text = "ขออนุมัติไปปฏิบัติราชการชั่วคราวในต่างประเทศ";
            sendInfo.ref_type = "hrm_ac_activity_requests";
            sendInfo.ref_seq = Int32.Parse(lblActSequence.Text.Trim());
            sendInfo.from_emp_seq = Convert.ToInt32(Session["EmpSeq"].ToString());
            sendInfo.to_emp_seq = Convert.ToInt32(cmbApprover.SelectedValue);
            sendInfo.remarks = null;
            sendInfo.message_status = "0";

            sendBLL.Insert(sendInfo);

            ((Forms.TaskLists)this.Parent.Page).ViewRequest();          
        }

        private bool directApprove = false;
        public string Approve()
        {
            rdoApproveStatus.SelectedValue = "A";
            rdoApproveStatus_SelectedIndexChanged(new Object(), new EventArgs());
            return cmdApprovedClick();
        }

        protected void cmdApproved_Click(object sender, EventArgs e)
        {
            cmdApprovedClick();
        }

        protected string cmdApprovedClick()
        {
            try
            {
                M_MessageSend sendInfo = new M_MessageSend();
                M_MessageReply replyInfo = new M_MessageReply();

                sendInfo.send_date = DateTime.Today;
                sendInfo.ref_no = sendBLL.GetNextSendRefNo("AC");
                sendInfo.send_text = "ขออนุมัติไปปฏิบัติราชการชั่วคราวในต่างประเทศ";
                sendInfo.ref_type = "hrm_ac_activity_requests";
                sendInfo.ref_seq = Int32.Parse(lblActSequence.Text.Trim());
                sendInfo.from_emp_seq = Convert.ToInt32(Session["EmpSeq"].ToString());
                //sendInfo.to_emp_seq = Convert.ToInt32(lblSenderSequence.Text.Trim());
                sendInfo.remarks = null;
                sendInfo.message_status = "0";

                if (!string.IsNullOrEmpty(cmbNextApprover.SelectedValue) && rdoApproveStatus.SelectedValue == "2")
                {
                    sendInfo.from_send_seq = Convert.ToInt32(lblSendSequence.Text.Trim());
                    sendInfo.to_emp_seq = Convert.ToInt32(cmbNextApprover.SelectedValue);
                    sendInfo.created_by = Convert.ToInt32(Session["EmpSeq"].ToString());
                    sendInfo.created_when = DateTime.Now;

                    sendBLL.Insert(sendInfo);
                    //sendBLL.Update(sendInfo);
                }
                else
                {
                    replyInfo.from_emp_seq = Convert.ToInt32(Session["EmpSeq"].ToString());
                    replyInfo.from_send_seq = Convert.ToInt32(lblSendSequence.Text.Trim());
                    replyInfo.to_emp_seq = Convert.ToInt32(lblSenderSequence.Text.Trim());
                    replyInfo.reply_date = DateTime.Now;
                    replyInfo.reply_type = rdoApproveStatus.SelectedValue;
                    replyInfo.reply_text = rdoApproveStatus.SelectedItem.Text;
                    replyInfo.created_by = Convert.ToInt32(Session["EmpSeq"].ToString());
                    replyInfo.created_when = DateTime.Now;

                    replyBLL.Insert(replyInfo);
                    actBLL.UpdateActivityRequests(Int32.Parse(lblRefSequence.Text.Trim()), Convert.ToInt32(Session["EmpSeq"].ToString()));
                }
                ((Forms.TaskLists) this.Parent.Page).ViewRequest();
            }
            catch (Exception ex)
            {
                string errorStr = ex.Message + " " + ex.InnerException;
                if (!directApprove) new Main().MessageAlert(Page, errorStr);
                return errorStr;
            }
            return "";
        }

        protected void cmdCancel_Click(object sender, EventArgs e)
        {
            ((Forms.TaskLists)this.Parent.Page).ViewRequest();
        }

    }
}